package utilities;

/**********************************************
 * Cours :			LOG120
 * Session :		Automne 2011
 * Groupe : 		03
 * Projet : 		Lab 1
 * Étudiant(e)(s) : Garcia Carrasco, Maria
 * 					Bolduc, Andrew
 * Code(s) perm. :  GARM05559006
 * 					BOLA03098701
 * Professeur : 	Yannick Boucher
 * Chargé de labo:  Jonathan Simard
 * Nom du fichier : ConnectionHandler.java
 * Date crée :      2011-09-27
 **********************************************
 * Historique des modifications
 **********************************************
 * 2011-09-27		Version initiale
 **********************************************
 */

/**
 * Cette classe a la responsabilité d'établir une connexion avec
 * le serveur, aussi que la fermer et retourné une réponse.
 * @author Maria Garcia Carrasco et Andrew Bolduc
 */

import interfaces.IConnectionHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class ConnectionHandler implements IConnectionHandler {
	
	private final String RESTRICTED_WORD = "commande> ";
	private Socket localServer;

	@Override
	public void openConnection(String connection) {
		try {
			localServer = new Socket(DecypherHost.getHost(connection), DecypherHost.getPort(connection));
		}
		catch(IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String getShape() {
		try {
			if(!localServer.isClosed()) {
				String line = "";
				PrintWriter out = new PrintWriter(new OutputStreamWriter(localServer.getOutputStream()), true);
	        	out.println("GET");
				BufferedReader reader = new BufferedReader(new InputStreamReader(localServer.getInputStream()));
				line = reader.readLine();
				if(line.equalsIgnoreCase(RESTRICTED_WORD)) {
					line = reader.readLine();
				}
				return line;
			}
			else {
				return null;
			}
	    }
		catch(IOException e) {
			e.printStackTrace();
	        return e.getMessage();
	    }
	}

	@Override
	public void closeConnection() {
		try {
			PrintWriter out = new PrintWriter(new OutputStreamWriter(localServer.getOutputStream()), true);
	    	out.println("END");
		}
		catch(IOException e) {
			e.printStackTrace();
		}
	}
	
}